<template>
  <van-nav-bar title="水老板-带你赚大钱" fixed class="nav-bar" />
  <div class="page-index">
    <div class="top-block">
      <van-tabs v-if="userType === 'user' && !isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0" v-model:active="activePage" @change="getProfitLossReport">
        <van-tab title="我的产品"></van-tab>
        <van-tab :title="simulatedProductInfo.productName"></van-tab>
      </van-tabs>
      <van-cell v-if="userType === 'user' && !isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0 && activePage === 0" class="main-fund no-bg" @click="openProductDetail(userPositionInfo, 1, true)">
        <template #title>
          <div class="title"></div>
        </template>
        <template #label>
          <div class="content-wrapper">
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(userPositionInfo?.assets) }}</span>
                <span class="unit">{{ formatAmountTextBySize(userPositionInfo?.assets) }}</span>
              </div>
              <div class="content-item-title">持有金额</div>
            </div>
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(userPositionInfo?.cost) }}</span>
                <span class="unit">{{ formatAmountTextBySize(userPositionInfo?.cost) }}</span>
              </div>
              <div class="content-item-title">持有成本</div>
            </div>
            <div class="content-item">
              <div class="content-item-value" :class="userPositionInfo?.symbol === '' ? '' : userPositionInfo?.symbol === '+' ? 'income' : 'loss'">
                <span>{{ userPositionInfo?.symbol }}</span>
                <span>{{ formatAmountBySize(Math.abs(userPositionInfo?.profitLoss || 0)) }}</span>
                <span class="unit">{{ formatAmountTextBySize(Math.abs(userPositionInfo?.profitLoss || 0)) }}</span>
              </div>
              <div class="content-item-title">浮动盈亏</div>
            </div>
          </div>
        </template>
      </van-cell>
      <van-cell v-if="userType === 'admin' || (userType === 'user' && !(!isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0)) || (userType === 'user' && !isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0 && activePage === 1)" class="main-fund no-bg" @click="openProductDetail(productInfo, 1, false)">
        <template #title>
          <div class="title" v-if="!(userType === 'user' && !isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0)">{{ simulatedProductInfo.productName }}</div>
        </template>
        <template #label>
          <div class="content-wrapper">
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(productInfo.totalAssets) }}</span>
                <span class="unit">{{ formatAmountTextBySize(productInfo.totalAssets) }}</span>
              </div>
              <div class="content-item-title">总持有资产</div>
            </div>
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(productInfo.totalCost) }}</span>
                <span class="unit">{{ formatAmountTextBySize(productInfo.totalCost) }}</span>
              </div>
              <div class="content-item-title">总持有成本</div>
            </div>
            <div class="content-item">
              <div class="content-item-value" :class="productInfo.symbol === '' ? '' : productInfo.symbol === '+' ? 'income' : 'loss'">
                <span>{{ productInfo.symbol }}</span>
                <span>{{ formatAmountBySize(Math.abs(productInfo.totalProfitLoss || 0)) }}</span>
                <span class="unit">{{ formatAmountTextBySize(Math.abs(productInfo.totalProfitLoss || 0)) }}</span>
              </div>
              <div class="content-item-title">总浮动盈亏</div>
            </div>
          </div>
        </template>
      </van-cell>
    </div>
    <van-cell class="mb-10 chart-block">
      <template #title>
        <div class="sub-title">浮动盈亏</div>
        <div id="charts-info" class="charts-info"></div>
      </template>
      <template #label>
        <van-tabs v-model:active="activeChartTime" @change="getProfitLossReport">
          <van-tab title="六个月"></van-tab>
          <van-tab title="本年"></van-tab>
          <van-tab title="成立以来"></van-tab>
        </van-tabs>
        <div ref="chartWrapper" class="chart-wrapper">
          <div id="profitLossChart" ref="ProfitLossChart" class="chart"></div>
        </div>
      </template>
    </van-cell>
    <!-- <div v-if="userType === 'admin'" class="product-list"> -->
    <div v-if="userType === 'admin' || (userType === 'user' && !(!isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0)) || (userType === 'user' && !isObjectEmpty(userPositionInfo) && userPositionInfo.assets !== 0 && activePage === 1)" class="product-list">
      <van-cell v-for="item in productList" :key="item.id" @click="openProductDetail(item, 2)">
        <template #title>
          <div class="title">{{ item.productNameAlias || item.productName }}</div>
        </template>
        <template #label>
          <div class="content-wrapper">
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(times(item.holdingUnits, item.currentNetValue)) }}</span>
                <span class="unit">{{ formatAmountTextBySize(times(item.holdingUnits, item.currentNetValue)) }}</span>
              </div>
              <div class="content-item-title">持有资产</div>
            </div>
            <van-divider vertical />
            <div class="content-item">
              <div class="content-item-value">
                <span>{{ formatAmountBySize(item.productCost) }}</span>
                <span class="unit">{{ formatAmountTextBySize(item.productCost) }}</span>
              </div>
              <div class="content-item-title">持有成本</div>
            </div>
            <van-divider vertical />
            <div class="content-item">
              <div class="content-item-value" :class="item.symbol === '' ? '' : item.symbol === '+' ? 'income' : 'loss'">
                <span>{{ item.symbol }}</span>
                <span>{{ formatAmountBySize(Math.abs(item.productProfitLoss || 0)) }}</span>
                <span class="unit">{{ formatAmountTextBySize(Math.abs(item.productProfitLoss || 0)) }}</span>
              </div>
              <div class="content-item-title">浮动盈亏</div>
            </div>
          </div>
        </template>
      </van-cell>
      <van-pagination
        v-if="productTotal > productParams.rows"
        v-model="productParams.page"
        :total-items="productTotal"
        :items-per-page="productParams.rows"
        :show-page-size="5"
        force-ellipses
        @change="getProductList"
      />
    </div>
    <van-floating-bubble v-if="userType === 'admin'" axis="xy" icon="setting-o" magnetic="x" @click="openSettingPanel" />
    <van-share-sheet v-model:show="showSettingPanel" :options="settingPanelOptions" @select="handleSettingPanelSelect" />
  </div>

  <ProductDetail ref="ProductDetailRef" />
</template>

<script setup>
import { ref, shallowRef, computed, onMounted, useTemplateRef } from 'vue'
import { onClickOutside } from '@vueuse/core'
import store from '@/stores'
import { storeToRefs } from 'pinia'
import {
  apiGetUserPositionInfo,
  apiGetProductInfoForUser,
  apiGetProductInfoForAdmin,
  apiGetSimulatedProductInfoForUser,
  apiGetSimulatedProductInfoForAdmin,
  apiGetSLBProfitLossReportForAdminNew,
  apiGetSLBProfitLossReportForUser,
  apiGetSLBProfitLossReportForUserNew
} from '@/api/user'
import { apiGetProductListForAdmin, apiGetProductListForUser } from '@/api/product'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { useRouter } from 'vue-router'
import ProductDetail from '../product/detail.vue'
import { getProfitLossReportParam, isObjectEmpty, formatAmountBySize, formatAmountTextBySize } from '@/utils/common'
import { times, minus } from '@/utils/calc'

const router = useRouter()
const { userInfo } = storeToRefs(store.user)
const { setUserPositionInfo } = store.user
const userType = computed(() => {
  return userInfo.value.type
})
const { setSlbInfo } = store.product
const activeChartTime = ref(3) // 默认显示购买以来
const userPositionInfo = ref({})
const activePage = ref(0) // 默认显示我的产品
// 基金产品
const productInfo = ref({})
// 拟合产品
const simulatedProductInfo = ref({})
const profitLossChart = shallowRef(null)
const productParams = ref({
  page: 1,
  rows: 10
})
const productTotal = ref(0)
const productList = ref([])
const showSettingPanel = ref(false)
const settingPanelOptions = ref([
  {
    name: '客户管理',
    icon: 'friends-o',
    path: '/customer'
  },
  {
    name: '持仓管理',
    icon: 'gold-coin-o',
    path: '/product'
  }
])

const ProductDetailRef = ref()
const chartWrapperRef = useTemplateRef('chartWrapper')
onClickOutside(chartWrapperRef, (event) => {
  if (profitLossChart.value) {
    profitLossChart.value.dispatchAction({
      type: 'hideTip'
    })
  }
})

const initCustomerInfo = async () => {
  // 客户
  await getUserPositionInfo()
  await getSimulatedProductInfo()
  getProductInfo()
  getProfitLossReport()
  getProductList()
}

const initAdminInfo = async () => {
  // 管理员
  await getSimulatedProductInfo()
  getProductInfo()
  getProfitLossReport()
  getProductList()
}

const getUserPositionInfo = async () => {
  return new Promise((resolve) => {
    apiGetUserPositionInfo().then((res) => {
      res.symbol = res.profitLoss === 0 ? '' : res.profitLoss > 0 ? '+' : '-'
      userPositionInfo.value = res
    }).finally(() => {
      setUserPositionInfo(userPositionInfo.value)
      resolve(true)
    })
  })
}

const getProductInfo = async () => {
  let result
  if (userType.value === 'user') {
    result = apiGetProductInfoForUser()
  } else {
    result = apiGetProductInfoForAdmin()
  }
  result.then((res) => {
    res.symbol = res.totalProfitLoss === 0 ? '' : res.totalProfitLoss > 0 ? '+' : '-'
    productInfo.value = Object.assign(res, {
      productCode: simulatedProductInfo.value.productCode,
      productName: simulatedProductInfo.value.productName,
      currentNetValue: simulatedProductInfo.value.currentNetValue
    })
  })
}

const getSimulatedProductInfo = async () => {
  let result
  if (userType.value === 'user') {
    result = apiGetSimulatedProductInfoForUser()
  } else {
    result = apiGetSimulatedProductInfoForAdmin()
  }
  result.then((res) => {
    res.symbol = res.totalProfitLoss === 0 ? '' : res.totalProfitLoss > 0 ? '+' : '-'
    simulatedProductInfo.value = res
    setSlbInfo(res)
  })
}

const getProfitLossReport = async () => {
  let result
  if (userType.value === 'user') {
    if (activePage.value === 1 || isObjectEmpty(userPositionInfo.value) || userPositionInfo.value.assets === 0) {
      // 基金产品
      result = apiGetSLBProfitLossReportForUserNew(getProfitLossReportParam(activeChartTime.value))
    } else {
      // 拟合产品
      result = apiGetSLBProfitLossReportForUser(getProfitLossReportParam(activeChartTime.value))
    }
  } else {
    result = apiGetSLBProfitLossReportForAdminNew(getProfitLossReportParam(activeChartTime.value))
  }
  result.then((res) => {
    initChart(res)
  })
}

function initChart(dataList) {
  if (profitLossChart.value) {
    profitLossChart.value.dispose()
  }
  const xAxisData = []
  const seriesData = []
  // 在处理前重新按时间戳排序
  const sortedData = [...dataList].sort((a, b) => 
    dayjs(a.transactionDate).valueOf() - dayjs(b.transactionDate).valueOf()
  )
  sortedData.forEach((item) => {
    xAxisData.push(dayjs(item.transactionDate).format('YYYY-MM-DD'))
    seriesData.push(item.totalProfitLoss)
  })
  let series = {
    name: '水老板一号',
    type: 'line',
    smooth: true,
    showSymbol: false,
    data: seriesData,
    markPoint: {
      data: [],
      label: {
        show: true,
        formatter: (params) => {
          return moneyFormat(params.value)
        }
      }
    }
  }
  profitLossChart.value = echarts.init(document.getElementById('profitLossChart'))
  profitLossChart.value.setOption({
    tooltip: {
      trigger: 'axis',
      // 让tooltip不可见
      // formatter: function() {
      //   return ''
      // },
      position: function (point, params, dom, rect, size) {
        // 完全居中计算
        const tooltipWidth = dom ? dom.offsetWidth : 0
        const x = (size.viewSize[0] - tooltipWidth) / 2
        return [x, 15]
      },
      valueFormatter: (value, dataIndex) => {
        const xAxisData = profitLossChart.value.getOption().xAxis[0].data
        const xValue = xAxisData[dataIndex]
        const infoDiv = document.getElementById('charts-info')
        infoDiv.innerHTML = `<span>总浮动盈亏 <strong style="color: ${value >= 0 ? '#ff4d4f' : '#52c41a'}">${value > 0 ? '+' : ''}${(value || 0).toFixed(2)}</strong>（元）</span> <span>${xValue}</span>`
        return `${ value ? (value / 10000).toFixed(2) + '万' : 0 }${ dataList[dataIndex].net_value !== undefined ?  ` | 净值：${ dataList[dataIndex].netValue }` : '' }` // 数据处理
      }
    },
    toolbox: {
      show: false
    },
    legend: {
      bottom: 0
    },
    grid: {
      top: '12%',
      left: '3%',
      right: '4%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      axisLabel: {
        margin: 20
      },
      data: xAxisData
    },
    yAxis: {
      type: 'value',
      scale: true,
      name: '盈亏（万元）',
      nameGap: 25,
      alignTicks: true,
      boundaryGap: [0.2, 0.2],
      axisLabel: {
        formatter: (v) => {
          const intPart = String(v).split('.')
          const intArr = intPart[0].split('')
          // if (intArr.length > 8) {
          //   return String(v).substring(0, intArr.length - 8) + '亿'
          // } else 
          if (intArr.length > 4) {
            return String(v).substring(0, intArr.length - 4) // + '万'
          } else {
            return String(v).substring(0, intArr.length) // + '元'
          }
        }
      }
    },
    series
  })
}

  function getProductList(page = 1) {
    productParams.value.page = page
    let result
    if (userType.value === 'user') {
      result = apiGetProductListForUser(productParams.value)
    } else {
      result = apiGetProductListForAdmin(productParams.value)
    }
    result.then((res) => {
      res.list.forEach((item) => {
        // item.productProfitLoss = minus(times(item.holdingUnits, item.currentNetValue), item.productCost)
        item.symbol = item.productProfitLoss === 0 ? '' : item.productProfitLoss > 0 ? '+' : '-'
      })
      // 重新排序：在持 > 已平；盈利 > 亏损；同状态下按盈亏金额排序
      res.list.sort((a, b) => {
        // 第一优先级：在持 vs 已平
        const aIsHolding = a.holdingUnits > 0
        const bIsHolding = b.holdingUnits > 0
        
        if (aIsHolding && !bIsHolding) {
          return -1 // a是在持，b是已平，a排在前面
        }
        if (!aIsHolding && bIsHolding) {
          return 1 // a是已平，b是在持，b排在前面
        }
        
        // 第二优先级：盈利 vs 亏损
        const aIsProfit = a.productProfitLoss > 0
        const bIsProfit = b.productProfitLoss > 0
        const aIsLoss = a.productProfitLoss < 0
        const bIsLoss = b.productProfitLoss < 0
        
        // 盈利的排在亏损的前面
        if (aIsProfit && bIsLoss) {
          return -1
        }
        if (aIsLoss && bIsProfit) {
          return 1
        }
        
        // 第三优先级：同状态下按盈亏金额绝对值排序（金额大的排前面）
        if (aIsProfit && bIsProfit) {
          // 两个都是盈利，盈利金额大的排前面
          return Math.abs(b.productProfitLoss) - Math.abs(a.productProfitLoss)
        }
        if (aIsLoss && bIsLoss) {
          // 两个都是亏损，亏损金额大的排前面（这样看起来更直观）
          return Math.abs(b.productProfitLoss) - Math.abs(a.productProfitLoss)
        }
        
        // 如果都是盈亏平衡，保持原顺序
        return 0
      })
      productList.value = res.list
      productTotal.value = res.total
    })
  }

const openSettingPanel = () => {
  showSettingPanel.value = true
}

const handleSettingPanelSelect = (option) => {
  router.push(option.path)
}

/**
 *
 * @param {*} product 产品信息
 * @param {*} type 1：拟合产品，2：普通产品
 * @param {*} isMyProduct 是否是我的产品
 */
const openProductDetail = (product, type, isMyProduct) => {
  if (type === 1 && !isMyProduct && userType.value === 'user') {
    return
  }
  ProductDetailRef.value.open(product, type)
}

onMounted(() => {
  if (userType.value === 'user') {
    // 客户
    initCustomerInfo()
  } else {
    // 管理员
    initAdminInfo()
  }
})
</script>

<style lang="less" scoped>
.nav-bar {
  background-color: var(--van-primary-color);
  --van-nav-bar-title-text-color: white;
}
.page-index {
  padding-top: var(--van-nav-bar-height);
  position: relative;
  .top-block {
    position: relative;
    background-color: white;
    overflow: hidden;
    .top-bg {
      background-color: var(--van-primary-color);
      position: absolute;
      width: 200vw;
      height: 200vw;
      border-radius: 50%;
      left: -50vw;
      bottom: 0;
    }
    .no-bg {
      background: transparent;
    }
    .title,
    .content-item-value,
    .content-item-title {
      color: #323232;
    }
    .van-tabs {
      margin-top: 5px;
    }
  }

  .van-pagination {
    background: var(--van-cell-background);
  }
  .product-list {
    position: sticky;
    top: var(--van-nav-bar-height);
  }
  :deep(.van-share-sheet__options) {
    justify-content: space-evenly;
  }
}
.title {
  font-size: 16px;
  font-weight: bold;
}
.main-fund {
  // padding-bottom: 50px;
  padding: 10px 16px 30px 16px;
  &::after {
    border-bottom-style: dashed;
  }
  .content-wrapper {
    margin-bottom: 0;
  }
}
.sub-title {
  font-size: 14px;
  font-weight: bold;
  color: #323232;
}
.charts-info {
  display: flex;
  justify-content: space-between;
  padding: 5px 12px 0 0;
  font-size: 12px;
}
.chart-block {
  padding-top: 0;
  .chart-wrapper {
  margin-top: 20px;
    height: 350px;
    .chart {
      height: 100%;
      width: 100%;
    }
  }
}
</style>
